package com.lcke.common.rest;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lcke.common.util.HttpContext;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 分页参数创建
 *
 * @author shenmk
 * @date 2017-04-05 22:25
 */
public class PageUtil {

    public static String pageNum = "page";

    public static String pageSize = "limit";

    /**
     * 获取layui table的分页参数
     *
     * @author shenmk
     * @Date 2019/1/25 22:13
     */
    public static <T> Page<T> startPage() {
        HttpServletRequest request = HttpContext.getRequest();
        Page<T> result = PageHelper.startPage(1, 10);
        if (request == null) {
            return result;
        }
        String pageNum = request.getParameter(PageUtil.pageNum);
        if (StrUtil.isNotBlank(pageNum)) {
            result.setPageNum(Integer.parseInt(pageNum));
        }
        String pageSize = request.getParameter(PageUtil.pageSize);
        if (StrUtil.isNotBlank(pageSize)) {
            result.setPageSize(Integer.parseInt(pageSize));
        }
        String orderBy = request.getParameter("orderBy");
        if (StrUtil.isNotBlank(orderBy)) {
            result.setOrderBy(orderBy);
        }
        return result;
    }

    /**
     * 创建layui能识别的分页响应参数
     *
     * @author shenmk
     * @Date 2019/1/25 22:14
     */
    public static <T> PageInfo<T> page(List<T> list) {
        PageInfo<T> pageInfo = new PageInfo<>();
        pageInfo.setData(list);
        if (list instanceof Page) {
            long total = ((Page<T>) list).getTotal();
            pageInfo.setTotal(total);
        } else {
            pageInfo.setTotal(list.size());
        }
        return pageInfo;
    }
}
